package cn.xkai.exercise.c;

import java.util.HashMap;
import java.util.Map;

/**
 * @description: 存在重复元素 II
 * <p>
 * 自己的思路：队列滑动
 * 借鉴的思路：哈希表判断重复计算索引差
 * 心得：队列contains操作耗时，链表搜索很慢
 * @author: kaixiang
 * @date: 2022-07-28
 **/
public class Solution101 {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(nums[i]) && i - map.get(nums[i]) <= k) {
                return true;
            }
            map.put(nums[i], i);
        }
        return false;
    }

    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 1, 2, 3};
        int k = 2;
        Solution101 solution101 = new Solution101();
        System.out.println(solution101.containsNearbyDuplicate(nums, k));
    }
}
